<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

class upgrade_class extends AWS_MODEL
{
	var $db_engine = '';
	
	public function setup()
	{
		if (!$this->db_engine = get_setting('db_engine'))
		{
			$this->db_engine = 'InnoDB';
		}
	}
	
	public function run_query($sql_query)
	{
		$sql_query = str_replace("\n", "\r", $sql_query);
		
		if ($db_table_querys = explode(";\r", str_replace(array('[#DB_PREFIX#]', '[#DB_ENGINE#]'), array(AWS_APP::config()->get('database')->prefix, $this->db_engine), $sql_query)))
		{
			foreach ($db_table_querys as $_sql)
			{
				if ($query_string = trim(str_replace(array(
					"\r", 
					"\n", 
					"\t"
				), '', $_sql)))
				{
					try {
						$this->db()->query($query_string);
					} catch (Exception $e) {
						return "<b>SQL:</b> <i>{$query_string}</i><br /><b>错误描述:</b> " . $e->getMessage();
					}
				}
			}
		}
	}
	
	public function upgrade_user_action_history()
	{
		$action_history_data = $this->query_all("SELECT history_id, associate_attached FROM " . get_table('user_action_history_data') . " WHERE associate_attached != ''");
		
		foreach ($action_history_data AS $key => $val)
		{
			if (is_numeric($val['associate_attached']))
			{
				$this->update('user_action_history', array('associate_attached' => $val['associate_attached']), 'history_id = ' . $val['history_id']);
				$this->update('user_action_history_data', array('associate_attached' => ''), 'history_id = ' . $val['history_id']);
			}
			else
			{
				$this->update('user_action_history', array('associate_attached' => '-1'), 'history_id = ' . $val['history_id']);
			}
		}
	}
}